import React, { useState, useEffect, useCallback } from "react";
import { Swiper, Tabs, Tag, Button, SpinLoading } from "antd-mobile";
import { 
    SearchOutline, 
    FireFill, 
    HeartFill, 
    StarFill, 
    UserOutline,
    EyeOutline,
    LikeOutline,
    MessageOutline
} from "antd-mobile-icons";
import { useNavigate } from "react-router-dom";
import { Toast } from "antd-mobile";
import VirtualList from "../../../components/VirtualList";

function Index() {
    const navigate = useNavigate();

    // 科普文章相关状态
    const [scienceArticles, setScienceArticles] = useState([]);
    const [currentPage, setCurrentPage] = useState(1);
    const [hasMore, setHasMore] = useState(true);
    const [isLoading, setIsLoading] = useState(false);
    const [isLoadingMore, setIsLoadingMore] = useState(false);
    const [isRefreshing, setIsRefreshing] = useState(false);
    const [activeTab, setActiveTab] = useState('all');
    const pageSize = 10;

    // 科普分类数据
    const categories = [
        { key: 'all', title: '全部', color: '#1890ff' },
        { key: 'disease', title: '疾病科普', color: '#f5222d' },
        { key: 'nutrition', title: '营养健康', color: '#52c41a' },
        { key: 'exercise', title: '运动健身', color: '#fa8c16' },
        { key: 'mental', title: '心理健康', color: '#722ed1' },
        { key: 'prevention', title: '预防保健', color: '#13c2c2' },
        { key: 'medicine', title: '用药指导', color: '#eb2f96' },
        { key: 'emergency', title: '急救知识', color: '#fa541c' }
    ];

    // 科普轮播图数据
    const scienceBanners = [
        {
            id: 1,
            title: '新冠病毒防护指南',
            subtitle: '科学防护，健康生活',
            imageUrl: 'https://img.freepik.com/free-vector/coronavirus-prevention-concept-illustration_114360-7488.jpg',
            description: '了解新冠病毒的传播途径和防护措施，掌握科学的防护方法。'
        },
        {
            id: 2,
            title: '高血压饮食指南',
            subtitle: '合理饮食，控制血压',
            imageUrl: 'https://img.freepik.com/free-vector/hypertension-concept-illustration_114360-7489.jpg',
            description: '高血压患者的饮食注意事项和营养搭配建议。'
        },
        {
            id: 3,
            title: '糖尿病管理手册',
            subtitle: '科学管理，稳定血糖',
            imageUrl: 'https://img.freepik.com/free-vector/diabetes-concept-illustration_114360-7490.jpg',
            description: '糖尿病患者的日常管理和血糖控制方法。'
        }
    ];

    // 科普文章数据获取
    const fetchScienceArticles = useCallback(async (page = 1, isLoadMore = false, category = 'all') => {
        if (isLoading || (isLoadMore && !hasMore)) return;
        
        try {
            if (isLoadMore) {
                setIsLoadingMore(true);
            } else {
                setIsLoading(true);
            }

            // 模拟API调用，实际项目中替换为真实API
            const mockData = generateMockScienceArticles(page, pageSize, category);
            
            if (page === 1) {
                setScienceArticles(mockData);
            } else {
                setScienceArticles(prev => [...prev, ...mockData]);
            }
            
            setCurrentPage(page);
            setHasMore(mockData.length === pageSize);
            
        } catch (error) {
            console.error("获取科普文章失败:", error);
            Toast.show({ content: "获取科普文章失败，请稍后重试", duration: 2000 });
        } finally {
            setIsLoading(false);
            setIsLoadingMore(false);
        }
    }, [isLoading, hasMore, pageSize]);

    // 生成模拟科普文章数据
    const generateMockScienceArticles = (page, size, category) => {
        const articles = [];
        const startIndex = (page - 1) * size;
        
        const categoryTitles = {
            all: ['健康科普', '疾病预防', '营养知识', '运动指导'],
            disease: ['高血压科普', '糖尿病科普', '心脏病科普', '癌症预防'],
            nutrition: ['营养搭配', '维生素知识', '膳食指南', '健康饮食'],
            exercise: ['运动健身', '瑜伽指导', '跑步技巧', '力量训练'],
            mental: ['心理健康', '情绪管理', '压力缓解', '睡眠改善'],
            prevention: ['疾病预防', '疫苗接种', '体检指南', '健康筛查'],
            medicine: ['用药指导', '药物知识', '副作用预防', '合理用药'],
            emergency: ['急救知识', '心肺复苏', '创伤处理', '中毒急救']
        };
        
        for (let i = 0; i < size; i++) {
            const index = startIndex + i;
            const titles = categoryTitles[category] || categoryTitles.all;
            const title = titles[Math.floor(Math.random() * titles.length)];
            
            articles.push({
                id: index + 1,
                title: `${title} ${index + 1}`,
                subtitle: `第${index + 1}期${title}科普`,
                summary: `这是一篇关于${title}的专业科普文章，由权威专家撰写，内容科学准确，通俗易懂。`,
                author: `科普专家${index + 1}`,
                publishTime: new Date(Date.now() - Math.random() * 30 * 24 * 60 * 60 * 1000).toLocaleDateString(),
                readCount: Math.floor(Math.random() * 10000) + 100,
                likeCount: Math.floor(Math.random() * 500) + 10,
                commentCount: Math.floor(Math.random() * 200) + 5,
                tags: [title, '科普', '健康'].slice(0, Math.floor(Math.random() * 3) + 1),
                image: `https://picsum.photos/80/60?random=${index + 1}`,
                category: category,
                isHot: Math.random() > 0.7,
                isRecommend: Math.random() > 0.8
            });
        }
        
        return articles;
    };

    // 刷新处理
    const handleRefresh = useCallback(() => {
        setIsRefreshing(true);
        fetchScienceArticles(1, false, activeTab).finally(() => {
            setIsRefreshing(false);
        });
    }, [fetchScienceArticles, activeTab]);

    // 标签切换处理
    const handleTabChange = (key) => {
        setActiveTab(key);
        setCurrentPage(1);
        setHasMore(true);
        fetchScienceArticles(1, false, key);
    };

    // 初始化数据
    useEffect(() => {
        fetchScienceArticles(1, false, activeTab);
    }, []);

    return (
        <div style={{
            minHeight: '100vh',
            backgroundColor: '#f5f5f5',
            paddingBottom: '60px'
        }}>
            {/* 搜索栏 */}
            <div style={{
                backgroundColor: '#fff',
                padding: '12px 16px',
                borderBottom: '1px solid #f0f0f0',
                position: 'sticky',
                top: 0,
                zIndex: 100
            }}>
                <div style={{
                    display: 'flex',
                    alignItems: 'center',
                    backgroundColor: '#f5f5f5',
                    borderRadius: '20px',
                    padding: '8px 16px',
                    cursor: 'pointer'
                }}
                onClick={() => navigate('/search')}
                >
                    <SearchOutline style={{ color: '#999', marginRight: '8px' }} />
                    <span style={{ color: '#999', fontSize: '14px' }}>搜索科普文章</span>
                </div>
            </div>

            {/* 分类标签 */}
            <div style={{
                backgroundColor: '#fff',
                padding: '16px',
                borderBottom: '1px solid #f0f0f0'
            }}>
                <div style={{
                    display: 'flex',
                    gap: '12px',
                    overflowX: 'auto',
                    WebkitOverflowScrolling: 'touch'
                }}>
                    {categories.map(category => (
                        <Tag
                            key={category.key}
                            color={activeTab === category.key ? category.color : 'default'}
                            fill={activeTab === category.key ? 'solid' : 'outline'}
                            style={{
                                flexShrink: 0,
                                fontSize: '14px',
                                padding: '6px 12px',
                                borderRadius: '16px'
                            }}
                            onClick={() => handleTabChange(category.key)}
                        >
                            {category.title}
                        </Tag>
                    ))}
                </div>
            </div>

            {/* 科普轮播图 */}
            <div style={{
                margin: '16px',
                backgroundColor: '#fff',
                borderRadius: '12px',
                overflow: 'hidden',
                boxShadow: '0 2px 8px rgba(0,0,0,0.1)'
            }}>
                <Swiper
                    style={{ height: '160px' }}
                    autoplay={true}
                    autoplayInterval={4000}
                    loop={true}
                    indicator={(total, current) => (
                        <div style={{
                            position: 'absolute',
                            left: '50%',
                            bottom: '12px',
                            transform: 'translateX(-50%)',
                            zIndex: 10,
                            display: 'flex',
                            gap: '8px',
                            alignItems: 'center'
                        }}>
                            {Array.from({ length: total }).map((_, index) => (
                                <div
                                    key={index}
                                    style={{
                                        width: '8px',
                                        height: '8px',
                                        backgroundColor: index === current ? '#1890ff' : 'rgba(24, 144, 255, 0.3)',
                                        borderRadius: '50%',
                                        transition: 'all 0.3s ease'
                                    }}
                                />
                            ))}
                        </div>
                    )}
                >
                    {
                        scienceBanners.map((item, index) => {
                            return <Swiper.Item key={index} style={{ height: '160px' }}>
                                <div
                                    onClick={() => navigate('/detail', {
                                        state: {
                                            title: item.title,
                                            subtitle: item.subtitle,
                                            image: item.imageUrl,
                                            description: item.description,
                                            tags: ['科普', '健康', '指南'],
                                            extraInfo: '科普文章的相关补充信息，帮助用户更好地了解内容。'
                                        }
                                    })}
                                    style={{
                                        cursor: 'pointer',
                                        width: '100%',
                                        height: '100%',
                                        position: 'relative'
                                    }}
                                >
                                    <img
                                        style={{
                                            width: '100%',
                                            height: '100%',
                                            objectFit: 'cover'
                                        }}
                                        src={item.imageUrl}
                                        alt={item.title}
                                    />
                                    <div style={{
                                        position: 'absolute',
                                        bottom: 0,
                                        left: 0,
                                        right: 0,
                                        background: 'linear-gradient(transparent, rgba(0,0,0,0.7))',
                                        padding: '20px',
                                        color: '#fff'
                                    }}>
                                        <div style={{
                                            fontSize: '16px',
                                            fontWeight: 'bold',
                                            marginBottom: '4px'
                                        }}>{item.title}</div>
                                        <div style={{
                                            fontSize: '12px',
                                            opacity: 0.9
                                        }}>{item.subtitle}</div>
                                    </div>
                                </div>
                            </Swiper.Item>
                        })
                    }
                </Swiper>
            </div>

            {/* 科普文章列表 */}
            <div style={{
                margin: '0 16px 16px',
                backgroundColor: '#fff',
                borderRadius: '12px',
                padding: '20px',
                boxShadow: '0 2px 8px rgba(0,0,0,0.1)'
            }}>
                <div style={{
                    fontSize: '18px',
                    fontWeight: 'bold',
                    marginBottom: '20px',
                    color: '#333',
                    display: 'flex',
                    alignItems: 'center'
                }}>
                    <div style={{
                        width: '4px',
                        height: '20px',
                        backgroundColor: '#1890ff',
                        marginRight: '12px',
                        borderRadius: '2px'
                    }}></div>
                    科普文章
                </div>
                
                <VirtualList
                    data={scienceArticles}
                    hasMore={hasMore}
                    loading={isLoading}
                    loadingMore={isLoadingMore}
                    onLoadMore={() => fetchScienceArticles(currentPage + 1, true, activeTab)}
                    onRefresh={handleRefresh}
                    refreshing={isRefreshing}
                    pullToRefresh={true}
                    containerHeight="60vh"
                    style={{ WebkitOverflowScrolling: 'touch', overscrollBehavior: 'contain' }}
                    loadMoreText="上拉加载更多科普文章"
                    loadingText="正在加载中..."
                    noMoreText="所有文章已加载完毕"
                    emptyText="暂无科普文章"
                    renderItem={(item) => (
                        <div
                            style={{
                                display: 'flex',
                                padding: '16px 0',
                                borderBottom: '1px solid #f0f0f0',
                                cursor: 'pointer'
                            }}
                            onClick={() => navigate('/detail', {
                                state: {
                                    title: item.title,
                                    subtitle: item.subtitle,
                                    image: item.image,
                                    description: item.summary,
                                    tags: item.tags,
                                    extraInfo: `作者：${item.author} | 发布时间：${item.publishTime} | 阅读量：${item.readCount} | 点赞数：${item.likeCount}`
                                }
                            })}
                        >
                            <img
                                src={item.image}
                                alt={item.title}
                                style={{
                                    width: '80px',
                                    height: '60px',
                                    borderRadius: '8px',
                                    marginRight: '16px',
                                    objectFit: 'cover'
                                }}
                            />
                            <div style={{ flex: 1, minWidth: 0 }}>
                                <div style={{
                                    fontSize: '16px',
                                    fontWeight: 'bold',
                                    color: '#333',
                                    marginBottom: '8px',
                                    lineHeight: '1.4',
                                    overflow: 'hidden',
                                    textOverflow: 'ellipsis',
                                    whiteSpace: 'nowrap'
                                }}>
                                    {item.title}
                                    {item.isHot && <FireFill style={{ color: '#ff4d4f', marginLeft: '4px' }} />}
                                    {item.isRecommend && <StarFill style={{ color: '#faad14', marginLeft: '4px' }} />}
                                </div>
                                <div style={{
                                    fontSize: '14px',
                                    color: '#666',
                                    marginBottom: '8px',
                                    lineHeight: '1.4',
                                    overflow: 'hidden',
                                    textOverflow: 'ellipsis',
                                    display: '-webkit-box',
                                    WebkitLineClamp: 2,
                                    WebkitBoxOrient: 'vertical'
                                }}>
                                    {item.summary}
                                </div>
                                <div style={{
                                    display: 'flex',
                                    alignItems: 'center',
                                    justifyContent: 'space-between',
                                    fontSize: '12px',
                                    color: '#999'
                                }}>
                                    <div style={{ display: 'flex', alignItems: 'center', gap: '16px' }}>
                                        <span style={{ display: 'flex', alignItems: 'center' }}>
                                            <EyeOutline style={{ marginRight: '4px' }} />
                                            {item.readCount}
                                        </span>
                                        <span style={{ display: 'flex', alignItems: 'center' }}>
                                            <LikeOutline style={{ marginRight: '4px' }} />
                                            {item.likeCount}
                                        </span>
                                        <span style={{ display: 'flex', alignItems: 'center' }}>
                                            <MessageOutline style={{ marginRight: '4px' }} />
                                            {item.commentCount}
                                        </span>
                                    </div>
                                    <span>{item.publishTime}</span>
                                </div>
                            </div>
                        </div>
                    )}
                />
            </div>
        </div>
    );
}

export default Index;
